using MQTTnet.Protocol;
using SheLife.Application.Interfaces;
using SheLife.Infrastructure.External;

namespace SheLife.Application.Services;

/// <summary>
/// MQTT发布服务实现
/// </summary>
public class MqttPublishService : IMqttPublishService
{
    private readonly IMqttService _mqttService;
    private readonly ILogger<MqttPublishService> _logger;

    public MqttPublishService(IMqttService mqttService, ILogger<MqttPublishService> logger)
    {
        _mqttService = mqttService;
        _logger = logger;
    }

    /// <summary>
    /// 发布生理周期更新消息
    /// </summary>
    public async Task PublishCycleUpdateAsync(Guid userId, int currentDay, DateTime? nextPeriodDate, int cycleLength)
    {
        try
        {
            var payload = new
            {
                UserId = userId,
                CurrentDay = currentDay,
                NextPeriodDate = nextPeriodDate?.ToString("yyyy-MM-dd"),
                CycleLength = cycleLength,
                Timestamp = DateTime.UtcNow
            };

            await _mqttService.PublishAsync($"shelife/cycle/update/{userId}", 
                System.Text.Json.JsonSerializer.Serialize(payload), 
                MqttQualityOfServiceLevel.AtLeastOnce);
            
            _logger.LogInformation("已发布生理周期更新消息: {UserId}, {CurrentDay}", userId, currentDay);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布生理周期更新消息失败: {UserId}", userId);
        }
    }

    /// <summary>
    /// 发布症状记录消息
    /// </summary>
    public async Task PublishSymptomRecordAsync(Guid userId, string symptomType, int severity, DateTime date)
    {
        try
        {
            var payload = new
            {
                UserId = userId,
                SymptomType = symptomType,
                Severity = severity,
                Date = date.ToString("yyyy-MM-dd"),
                Timestamp = DateTime.UtcNow
            };

            await _mqttService.PublishAsync($"shelife/symptom/record/{userId}", 
                System.Text.Json.JsonSerializer.Serialize(payload), 
                MqttQualityOfServiceLevel.AtLeastOnce);
            
            _logger.LogInformation("已发布症状记录消息: {UserId}, {SymptomType}", userId, symptomType);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布症状记录消息失败: {UserId}, {SymptomType}", userId, symptomType);
        }
    }

    /// <summary>
    /// 发布基础体温记录消息
    /// </summary>
    public async Task PublishTemperatureRecordAsync(Guid userId, decimal temperature, DateTime date)
    {
        try
        {
            var payload = new
            {
                UserId = userId,
                Temperature = temperature,
                Date = date.ToString("yyyy-MM-dd"),
                Timestamp = DateTime.UtcNow
            };

            await _mqttService.PublishAsync($"shelife/temperature/record/{userId}", 
                System.Text.Json.JsonSerializer.Serialize(payload), 
                MqttQualityOfServiceLevel.AtLeastOnce);
            
            _logger.LogInformation("已发布基础体温记录消息: {UserId}, {Temperature}", userId, temperature);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布基础体温记录消息失败: {UserId}", userId);
        }
    }

    /// <summary>
    /// 发布排卵期预测消息
    /// </summary>
    public async Task PublishOvulationPredictionAsync(Guid userId, DateTime? ovulationDate)
    {
        try
        {
            var payload = new
            {
                UserId = userId,
                OvulationDate = ovulationDate?.ToString("yyyy-MM-dd"),
                Timestamp = DateTime.UtcNow
            };

            await _mqttService.PublishAsync($"shelife/ovulation/prediction/{userId}", 
                System.Text.Json.JsonSerializer.Serialize(payload), 
                MqttQualityOfServiceLevel.AtLeastOnce);
            
            _logger.LogInformation("已发布排卵期预测消息: {UserId}, {OvulationDate}", userId, ovulationDate);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布排卵期预测消息失败: {UserId}", userId);
        }
    }

    /// <summary>
    /// 发布健康提醒消息
    /// </summary>
    public async Task PublishHealthReminderAsync(Guid userId, string reminderType, string message)
    {
        try
        {
            var payload = new
            {
                UserId = userId,
                ReminderType = reminderType,
                Message = message,
                Timestamp = DateTime.UtcNow
            };

            await _mqttService.PublishAsync($"shelife/reminder/health/{userId}", 
                System.Text.Json.JsonSerializer.Serialize(payload), 
                MqttQualityOfServiceLevel.AtLeastOnce);
            
            _logger.LogInformation("已发布健康提醒消息: {UserId}, {ReminderType}", userId, reminderType);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发布健康提醒消息失败: {UserId}, {ReminderType}", userId, reminderType);
        }
    }
}